//
//  LYWebViewController.swift
//  LYOnlineBanking
//
//  Created by 李永彬 on 2025/8/2.
//

import UIKit
import WebKit
import SnapKit
import StoreKit

class LYWebViewController: LYBaseViewController, WKScriptMessageHandler, WKNavigationDelegate {
    
    // MARK: - Properties
    private var webView: WKWebView? = nil
    private var progressView = UIProgressView(progressViewStyle: .bar)
    
    var urlString: String? = nil
    
    var isFollowOrder: Bool = false
    var isPresent: Bool = false
    
    // MARK: - Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        setupWebView()
        loadWebContent()
        setupCustomBackButton()
    }
    
    private func setupCustomBackButton() {
        let backButton = UIBarButtonItem.init(image: UIImage(named: "back"),
                                              style: .plain,
                                              target: self,
                                              action: #selector(backButtonTapped))
        navigationItem.leftBarButtonItem = backButton
        navigationItem.hidesBackButton = true
    }
    
    @objc private func backButtonTapped() {
        
        if let webView = webView,
            webView.canGoBack {
            webView.goBack()
        } else {
            if isFollowOrder {
                if isPresent {
                    self.dismiss(animated: true)
                } else {
                    self.navigationController?.popToRootViewController(animated: true)
                }
            } else {
                if isPresent {
                    self.dismiss(animated: true)
                } else {
                    self.navigationController?.popViewController(animated: true)
                }
            }
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        webView?.addObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress), options: .new, context: nil)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        webView?.removeObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress))
    }
    
    deinit {
        webView?.configuration.userContentController.removeScriptMessageHandler(forName: "iosListener")
        webView?.configuration.userContentController.removeScriptMessageHandler(forName: "navigationListener")
    }
    
    // MARK: - UI Setup
    private func setupUI() {
        view.backgroundColor = .white
        setupProgressView()
    }
    
    private func setupProgressView() {
        progressView.tintColor = UIColor(hex: "#1E4FF3")
        progressView.trackTintColor = .clear
        
        view.addSubview(progressView)
        
        progressView.snp.makeConstraints { make in
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
            make.leading.trailing.equalToSuperview()
            make.height.equalTo(2)
        }
    }
    
    // MARK: - WebView Setup
    private func setupWebView() {
        let config = WKWebViewConfiguration()
        let userContentController = WKUserContentController()
        
        // 添加消息处理器
        userContentController.add(self, name: "aviarium")
        userContentController.add(self, name: "existacle")
        userContentController.add(self, name: "year")
        userContentController.add(self, name: "cardischoolality")
        userContentController.add(self, name: "dynaette")
        userContentController.add(self, name: "brevimemoryty")
        
        config.userContentController = userContentController
        
        webView = WKWebView(frame: .zero, configuration: config)
        webView?.navigationDelegate = self
        webView?.uiDelegate = self
        view.insertSubview(webView!, belowSubview: progressView)
        
        webView?.snp.makeConstraints { make in
            make.top.equalTo(progressView.snp.bottom)
            make.leading.trailing.bottom.equalToSuperview()
        }
    }
    
    // MARK: - Load Content
    private func loadWebContent() {
        let queryString = NetworkManager.shared.commonParameters.toURLQueryString()
        var urlString = self.urlString
        
        if let url = urlString, url.contains("?") {
            urlString = "\(urlString ?? "")&\(queryString)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
        } else {
            urlString = "\(urlString ?? "")?\(queryString)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
        }
        
         if let urlString = urlString,
            let url = URL(string: urlString) {
             webView?.load(URLRequest(url: url))
         }
    }
    
    // MARK: - Progress Observer
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "estimatedProgress",
           let webView = webView {
            progressView.progress = Float(webView.estimatedProgress)
            progressView.isHidden = webView.estimatedProgress >= 1.0
        }
    }
    
    // MARK: - WKScriptMessageHandler
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        
        switch message.name {
        case "aviarium"://风控埋点
            handleMaiDian(message: message)
        case "existacle"://跳转原生或者H5
            handleJumpAppOrH5(message: message)
        case "year"://关闭当前 H5
            closeCurrentH5(message: message)
        case "cardischoolality"://回到 App 首页
            jumpToHomeVc(message: message)
        case "dynaette"://H5 页面里的拨打电话（打开系统邮箱）
            callPhone(message: message)
        case "brevimemoryty"://调用 App 应用评分，弹出系统评分
            appMark(message: message)
        default:
            break
        }
    }
    
    private func handleMaiDian(message: WKScriptMessage) {
        guard let body = message.body as? [Any],
              body.count >= 2 else {
            print("无效的消息格式")
            return
        }
        
        let productId: Int
        if let number = body[0] as? Int {
            productId = number
        } else if let string = body[0] as? String, let value = Int(string) {
            productId = value
        } else {
            print("无法解析 productId")
            return
        }
        
        guard let orderNum = body[1] as? String else {
            print("无法解析 orderNum")
            return
        }
        
        LYTrackingManager.uploadRiskTracking(
            sceneType: .endLoan,
            productId: productId,
            orderNum: orderNum,
            startTimeStamp: Date().timeIntervalSince1970,
            endTimeStamp: Date().timeIntervalSince1970
        )
    }
    
    private func handleJumpAppOrH5(message: WKScriptMessage) {
        if let url = message.body as? String {
            if url.hasPrefix("http") || url.hasPrefix("https") {
                let webviewVC = LYWebViewController()
                webviewVC.urlString = url
                self.navigationController?.pushViewController(webviewVC, animated: true)
            } else {
                LYSchemeManager.shared.parser(url)
            }
        }
    }
    
    private func closeCurrentH5(message: WKScriptMessage) {
        self.navigationController?.popViewController(animated: true)
    }
    
    private func jumpToHomeVc(message: WKScriptMessage) {
        self.navigationController?.popToRootViewController(animated: true)
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
            if let mainVC = UIApplication.shared.currentKeyWindow?.rootViewController as? LYMainViewController {
                mainVC.changeViewController(to: 0)
                if let vc = mainVC.children.first,
                   let homeVC = (vc as? LYNavigationController)?.viewControllers.first as? LYEmohViewController {
                    homeVC.updateData()
                }
            }
        }
    }
    
    private func callPhone(message: WKScriptMessage) {
      
        if let email = message.body as? String {
            openEmailComposer(email)
        }
    }
    
    func openEmailComposer(_ email: String) {
        let phone = LYUserDefaults.shared.getString(forKey: phoneNumKey) ?? ""
        let urlstr = "mailto:\(email)?body=Tunai Pasti,\(phone):"
        let mailtoUrlString = urlstr.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
        
        if let url = URL(string: mailtoUrlString) {
            if UIApplication.shared.canOpenURL(url) {
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            }
        }
    }
    
    private func appMark(message: WKScriptMessage) {
        SKStoreReviewController.requestReview()
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        // 或者设置导航栏标题
        self.title = webView.title
    }
}

// MARK: - WKNavigationDelegate & WKUIDelegate
extension LYWebViewController: WKUIDelegate {
    // 实现所需的委托方法
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        decisionHandler(.allow)
        
        if let url = navigationAction.request.url {
            print("用户点击了链接: \(url.absoluteString)")
            
            // 可以在这里拦截特定链接
            if url.absoluteString.contains("special-link") {
                // 处理特殊链接
                decisionHandler(.cancel)
                return
            }
        }
    }
}
